home *** CD-ROM | disk | FTP | other *** search
/ Software of the Month Club 2000 October / Software of the Month - Ultimate Collection Shareware 277.iso / pc / PROGRAMS / UTILITY / WINLINUX / DATA1.CAB / programs_-_kernel_source / MM / FILEMAP.C < prev    next >
Encoding:
C/C++ Source or Header  |  1999-09-17  |  42.7 KB  |  1,734 lines

  1. /*
  2.  *    linux/mm/filemap.c
  3.  *
  4.  * Copyright (C) 1994, 1995  Linus Torvalds
  5.  */
  6.  
  7. /*
  8.  * This file handles the generic file mmap semantics used by
  9.  * most "normal" filesystems (but you don't /have/ to use this:
  10.  * the NFS filesystem used to do this differently, for example)
  11.  */
  12. #include <linux/malloc.h>
  13. #include <linux/shm.h>
  14. #include <linux/mman.h>
  15. #include <linux/locks.h>
  16. #include <linux/pagemap.h>
  17. #include <linux/swap.h>
  18. #include <linux/smp_lock.h>
  19. #include <linux/blkdev.h>
  20. #include <linux/file.h>
  21. #include <linux/swapctl.h>
  22. #include <linux/slab.h>
  23.  
  24. #include <asm/pgtable.h>
  25. #include <asm/uaccess.h>
  26.  
  27. /*
  28.  * Shared mappings implemented 30.11.1994. It's not fully working yet,
  29.  * though.
  30.  *
  31.  * Shared mappings now work. 15.8.1995  Bruno.
  32.  */
  33.  
  34. unsigned long page_cache_size = 0;
  35. struct page * page_hash_table[PAGE_HASH_SIZE];
  36.  
  37. /*
  38.  * Simple routines for both non-shared and shared mappings.
  39.  */
  40.  
  41. #define release_page(page) __free_page((page))
  42.  
  43. /* 
  44.  * Define a request structure for outstanding page write requests
  45.  * to the background page io daemon
  46.  */
  47.  
  48. struct pio_request 
  49. {
  50.     struct pio_request *    next;
  51.     struct file *        file;
  52.     unsigned long        offset;
  53.     unsigned long        page;
  54. };
  55. static struct pio_request *pio_first = NULL, **pio_last = &pio_first;
  56. static kmem_cache_t *pio_request_cache;
  57. static struct wait_queue *pio_wait = NULL;
  58.  
  59. static inline void 
  60. make_pio_request(struct file *, unsigned long, unsigned long);
  61.  
  62.  
  63. /*
  64.  * Invalidate the pages of an inode, removing all pages that aren't
  65.  * locked down (those are sure to be up-to-date anyway, so we shouldn't
  66.  * invalidate them).
  67.  */
  68. void invalidate_inode_pages(struct inode * inode)
  69. {
  70.     struct page ** p;
  71.     struct page * page;
  72.  
  73.     p = &inode->i_pages;
  74.     while ((page = *p) != NULL) {
  75.         if (PageLocked(page)) {
  76.             p = &page->next;
  77.             continue;
  78.         }
  79.         inode->i_nrpages--;
  80.         if ((*p = page->next) != NULL)
  81.             (*p)->prev = page->prev;
  82.         page->next = NULL;
  83.         page->prev = NULL;
  84.         remove_page_from_hash_queue(page);
  85.         page->inode = NULL;
  86.         __free_page(page);
  87.         continue;
  88.     }
  89. }
  90.  
  91. /*
  92.  * Truncate the page cache at a set offset, removing the pages
  93.  * that are beyond that offset (and zeroing out partial pages).
  94.  */
  95. void truncate_inode_pages(struct inode * inode, unsigned long start)
  96. {
  97.     struct page ** p;
  98.     struct page * page;
  99.  
  100. repeat:
  101.     p = &inode->i_pages;
  102.     while ((page = *p) != NULL) {
  103.         unsigned long offset = page->offset;
  104.  
  105.         /* page wholly truncated - free it */
  106.         if (offset >= start) {
  107.             if (PageLocked(page)) {
  108.                 wait_on_page(page);
  109.                 goto repeat;
  110.             }
  111.             inode->i_nrpages--;
  112.             if ((*p = page->next) != NULL)
  113.                 (*p)->prev = page->prev;
  114.             page->next = NULL;
  115.             page->prev = NULL;
  116.             remove_page_from_hash_queue(page);
  117.             page->inode = NULL;
  118.             __free_page(page);
  119.             continue;
  120.         }
  121.         p = &page->next;
  122.         offset = start - offset;
  123.         /* partial truncate, clear end of page */
  124.         if (offset < PAGE_SIZE) {
  125.             unsigned long address = page_address(page);
  126.             memset((void *) (offset + address), 0, PAGE_SIZE - offset);
  127.             flush_page_to_ram(address);
  128.         }
  129.     }
  130. }
  131.  
  132. /*
  133.  * Remove a page from the page cache and free it.
  134.  */
  135. void remove_inode_page(struct page *page)
  136. {
  137.     remove_page_from_hash_queue(page);
  138.     remove_page_from_inode_queue(page);
  139.     __free_page(page);
  140. }
  141.  
  142. int shrink_mmap(int priority, int gfp_mask)
  143. {
  144.     static unsigned long clock = 0;
  145.     unsigned long limit = num_physpages;
  146.     struct page * page;
  147.     int count;
  148.  
  149.     count = limit >> priority;
  150.  
  151.     page = mem_map + clock;
  152.     do {
  153.         int referenced;
  154.  
  155.         /* This works even in the presence of PageSkip because
  156.          * the first two entries at the beginning of a hole will
  157.          * be marked, not just the first.
  158.          */
  159.         page++;
  160.         clock++;
  161.         if (clock >= max_mapnr) {
  162.             clock = 0;
  163.             page = mem_map;
  164.         }
  165.         if (PageSkip(page)) {
  166.             /* next_hash is overloaded for PageSkip */
  167.             page = page->next_hash;
  168.             clock = page - mem_map;
  169.         }
  170.         
  171.         referenced = test_and_clear_bit(PG_referenced, &page->flags);
  172.  
  173.         if (PageLocked(page))
  174.             continue;
  175.  
  176.         if ((gfp_mask & __GFP_DMA) && !PageDMA(page))
  177.             continue;
  178.  
  179.         /* We can't free pages unless there's just one user */
  180.         if (atomic_read(&page->count) != 1)
  181.             continue;
  182.  
  183.         count--;
  184.  
  185.         /*
  186.          * Is it a page swap page? If so, we want to
  187.          * drop it if it is no longer used, even if it
  188.          * were to be marked referenced..
  189.          */
  190.         if (PageSwapCache(page)) {
  191.             if (referenced && swap_count(page->offset) != 1)
  192.                 continue;
  193.             delete_from_swap_cache(page);
  194.             return 1;
  195.         }    
  196.  
  197.         if (referenced)
  198.             continue;
  199.  
  200.         /* Is it a buffer page? */
  201.         if (page->buffers) {
  202.             if (buffer_under_min())
  203.                 continue;
  204.             if (!try_to_free_buffers(page))
  205.                 continue;
  206.             return 1;
  207.         }
  208.  
  209.         /* is it a page-cache page? */
  210.         if (page->inode) {
  211.             if (pgcache_under_min())
  212.                 continue;
  213.             remove_inode_page(page);
  214.             return 1;
  215.         }
  216.  
  217.     } while (count > 0);
  218.     return 0;
  219. }
  220.  
  221. /*
  222.  * Update a page cache copy, when we're doing a "write()" system call
  223.  * See also "update_vm_cache()".
  224.  */
  225. void update_vm_cache(struct inode * inode, unsigned long pos, const char * buf, int count)
  226. {
  227.     unsigned long offset, len;
  228.  
  229.     offset = (pos & ~PAGE_MASK);
  230.     pos = pos & PAGE_MASK;
  231.     len = PAGE_SIZE - offset;
  232.     do {
  233.         struct page * page;
  234.  
  235.         if (len > count)
  236.             len = count;
  237.         page = find_page(inode, pos);
  238.         if (page) {
  239.             wait_on_page(page);
  240.             memcpy((void *) (offset + page_address(page)), buf, len);
  241.             release_page(page);
  242.         }
  243.         count -= len;
  244.         buf += len;
  245.         len = PAGE_SIZE;
  246.         offset = 0;
  247.         pos += PAGE_SIZE;
  248.     } while (count);
  249. }
  250.  
  251. static inline void add_to_page_cache(struct page * page,
  252.     struct inode * inode, unsigned long offset,
  253.     struct page **hash)
  254. {
  255.     atomic_inc(&page->count);
  256.     page->flags = (page->flags & ~((1 << PG_uptodate) | (1 << PG_error))) | (1 << PG_referenced);
  257.     page->offset = offset;
  258.     add_page_to_inode_queue(inode, page);
  259.     __add_page_to_hash_queue(page, hash);
  260. }
  261.  
  262. /*
  263.  * Try to read ahead in the file. "page_cache" is a potentially free page
  264.  * that we could use for the cache (if it is 0 we can try to create one,
  265.  * this is all overlapped with the IO on the previous page finishing anyway)
  266.  */
  267. static unsigned long try_to_read_ahead(struct file * file,
  268.                 unsigned long offset, unsigned long page_cache)
  269. {
  270.     struct inode *inode = file->f_dentry->d_inode;
  271.     struct page * page;
  272.     struct page ** hash;
  273.  
  274.     offset &= PAGE_MASK;
  275.     switch (page_cache) {
  276.     case 0:
  277.         page_cache = __get_free_page(GFP_USER);
  278.         if (!page_cache)
  279.             break;
  280.     default:
  281.         if (offset >= inode->i_size)
  282.             break;
  283.         hash = page_hash(inode, offset);
  284.         page = __find_page(inode, offset, *hash);
  285.         if (!page) {
  286.             /*
  287.              * Ok, add the new page to the hash-queues...
  288.              */
  289.             page = mem_map + MAP_NR(page_cache);
  290.             add_to_page_cache(page, inode, offset, hash);
  291.             inode->i_op->readpage(file, page);
  292.             page_cache = 0;
  293.         }
  294.         release_page(page);
  295.     }
  296.     return page_cache;
  297. }
  298.  
  299. /* 
  300.  * Wait for IO to complete on a locked page.
  301.  *
  302.  * This must be called with the caller "holding" the page,
  303.  * ie with increased "page->count" so that the page won't
  304.  * go away during the wait..
  305.  */
  306. void __wait_on_page(struct page *page)
  307. {
  308.     struct task_struct *tsk = current;
  309.     struct wait_queue wait;
  310.  
  311.     wait.task = tsk;
  312.     add_wait_queue(&page->wait, &wait);
  313. repeat:
  314.     tsk->state = TASK_UNINTERRUPTIBLE;
  315.     run_task_queue(&tq_disk);
  316.     if (PageLocked(page)) {
  317.         schedule();
  318.         goto repeat;
  319.     }
  320.     tsk->state = TASK_RUNNING;
  321.     remove_wait_queue(&page->wait, &wait);
  322. }
  323.  
  324. #if 0
  325. #define PROFILE_READAHEAD
  326. #define DEBUG_READAHEAD
  327. #endif
  328.  
  329. /*
  330.  * Read-ahead profiling information
  331.  * --------------------------------
  332.  * Every PROFILE_MAXREADCOUNT, the following information is written 
  333.  * to the syslog:
  334.  *   Percentage of asynchronous read-ahead.
  335.  *   Average of read-ahead fields context value.
  336.  * If DEBUG_READAHEAD is defined, a snapshot of these fields is written 
  337.  * to the syslog.
  338.  */
  339.  
  340. #ifdef PROFILE_READAHEAD
  341.  
  342. #define PROFILE_MAXREADCOUNT 1000
  343.  
  344. static unsigned long total_reada;
  345. static unsigned long total_async;
  346. static unsigned long total_ramax;
  347. static unsigned long total_ralen;
  348. static unsigned long total_rawin;
  349.  
  350. static void profile_readahead(int async, struct file *filp)
  351. {
  352.     unsigned long flags;
  353.  
  354.     ++total_reada;
  355.     if (async)
  356.         ++total_async;
  357.  
  358.     total_ramax    += filp->f_ramax;
  359.     total_ralen    += filp->f_ralen;
  360.     total_rawin    += filp->f_rawin;
  361.  
  362.     if (total_reada > PROFILE_MAXREADCOUNT) {
  363.         save_flags(flags);
  364.         cli();
  365.         if (!(total_reada > PROFILE_MAXREADCOUNT)) {
  366.             restore_flags(flags);
  367.             return;
  368.         }
  369.  
  370.         printk("Readahead average:  max=%ld, len=%ld, win=%ld, async=%ld%%\n",
  371.             total_ramax/total_reada,
  372.             total_ralen/total_reada,
  373.             total_rawin/total_reada,
  374.             (total_async*100)/total_reada);
  375. #ifdef DEBUG_READAHEAD
  376.         printk("Readahead snapshot: max=%ld, len=%ld, win=%ld, raend=%ld\n",
  377.             filp->f_ramax, filp->f_ralen, filp->f_rawin, filp->f_raend);
  378. #endif
  379.  
  380.         total_reada    = 0;
  381.         total_async    = 0;
  382.         total_ramax    = 0;
  383.         total_ralen    = 0;
  384.         total_rawin    = 0;
  385.  
  386.         restore_flags(flags);
  387.     }
  388. }
  389. #endif  /* defined PROFILE_READAHEAD */
  390.  
  391. /*
  392.  * Read-ahead context:
  393.  * -------------------
  394.  * The read ahead context fields of the "struct file" are the following:
  395.  * - f_raend : position of the first byte after the last page we tried to
  396.  *             read ahead.
  397.  * - f_ramax : current read-ahead maximum size.
  398.  * - f_ralen : length of the current IO read block we tried to read-ahead.
  399.  * - f_rawin : length of the current read-ahead window.
  400.  *             if last read-ahead was synchronous then
  401.  *                  f_rawin = f_ralen
  402.  *             otherwise (was asynchronous)
  403.  *                  f_rawin = previous value of f_ralen + f_ralen
  404.  *
  405.  * Read-ahead limits:
  406.  * ------------------
  407.  * MIN_READAHEAD   : minimum read-ahead size when read-ahead.
  408.  * MAX_READAHEAD   : maximum read-ahead size when read-ahead.
  409.  *
  410.  * Synchronous read-ahead benefits:
  411.  * --------------------------------
  412.  * Using reasonable IO xfer length from peripheral devices increase system 
  413.  * performances.
  414.  * Reasonable means, in this context, not too large but not too small.
  415.  * The actual maximum value is:
  416.  *    MAX_READAHEAD + PAGE_SIZE = 76k is CONFIG_READA_SMALL is undefined
  417.  *      and 32K if defined (4K page size assumed).
  418.  *
  419.  * Asynchronous read-ahead benefits:
  420.  * ---------------------------------
  421.  * Overlapping next read request and user process execution increase system 
  422.  * performance.
  423.  *
  424.  * Read-ahead risks:
  425.  * -----------------
  426.  * We have to guess which further data are needed by the user process.
  427.  * If these data are often not really needed, it's bad for system 
  428.  * performances.
  429.  * However, we know that files are often accessed sequentially by 
  430.  * application programs and it seems that it is possible to have some good 
  431.  * strategy in that guessing.
  432.  * We only try to read-ahead files that seems to be read sequentially.
  433.  *
  434.  * Asynchronous read-ahead risks:
  435.  * ------------------------------
  436.  * In order to maximize overlapping, we must start some asynchronous read 
  437.  * request from the device, as soon as possible.
  438.  * We must be very careful about:
  439.  * - The number of effective pending IO read requests.
  440.  *   ONE seems to be the only reasonable value.
  441.  * - The total memory pool usage for the file access stream.
  442.  *   This maximum memory usage is implicitly 2 IO read chunks:
  443.  *   2*(MAX_READAHEAD + PAGE_SIZE) = 156K if CONFIG_READA_SMALL is undefined,
  444.  *   64k if defined (4K page size assumed).
  445.  */
  446.  
  447. static inline int get_max_readahead(struct inode * inode)
  448. {
  449.     if (!inode->i_dev || !max_readahead[MAJOR(inode->i_dev)])
  450.         return MAX_READAHEAD;
  451.     return max_readahead[MAJOR(inode->i_dev)][MINOR(inode->i_dev)];
  452. }
  453.  
  454. static inline unsigned long generic_file_readahead(int reada_ok,
  455.     struct file * filp, struct inode * inode,
  456.     unsigned long ppos, struct page * page, unsigned long page_cache)
  457. {
  458.     unsigned long max_ahead, ahead;
  459.     unsigned long raend;
  460.     int max_readahead = get_max_readahead(inode);
  461.  
  462.     raend = filp->f_raend & PAGE_MASK;
  463.     max_ahead = 0;
  464.  
  465. /*
  466.  * The current page is locked.
  467.  * If the current position is inside the previous read IO request, do not
  468.  * try to reread previously read ahead pages.
  469.  * Otherwise decide or not to read ahead some pages synchronously.
  470.  * If we are not going to read ahead, set the read ahead context for this 
  471.  * page only.
  472.  */
  473.     if (PageLocked(page)) {
  474.         if (!filp->f_ralen || ppos >= raend || ppos + filp->f_ralen < raend) {
  475.             raend = ppos;
  476.             if (raend < inode->i_size)
  477.                 max_ahead = filp->f_ramax;
  478.             filp->f_rawin = 0;
  479.             filp->f_ralen = PAGE_SIZE;
  480.             if (!max_ahead) {
  481.                 filp->f_raend  = ppos + filp->f_ralen;
  482.                 filp->f_rawin += filp->f_ralen;
  483.             }
  484.         }
  485.     }
  486. /*
  487.  * The current page is not locked.
  488.  * If we were reading ahead and,
  489.  * if the current max read ahead size is not zero and,
  490.  * if the current position is inside the last read-ahead IO request,
  491.  *   it is the moment to try to read ahead asynchronously.
  492.  * We will later force unplug device in order to force asynchronous read IO.
  493.  */
  494.     else if (reada_ok && filp->f_ramax && raend >= PAGE_SIZE &&
  495.              ppos <= raend && ppos + filp->f_ralen >= raend) {
  496. /*
  497.  * Add ONE page to max_ahead in order to try to have about the same IO max size
  498.  * as synchronous read-ahead (MAX_READAHEAD + 1)*PAGE_SIZE.
  499.  * Compute the position of the last page we have tried to read in order to 
  500.  * begin to read ahead just at the next page.
  501.  */
  502.         raend -= PAGE_SIZE;
  503.         if (raend < inode->i_size)
  504.             max_ahead = filp->f_ramax + PAGE_SIZE;
  505.  
  506.         if (max_ahead) {
  507.             filp->f_rawin = filp->f_ralen;
  508.             filp->f_ralen = 0;
  509.             reada_ok      = 2;
  510.         }
  511.     }
  512. /*
  513.  * Try to read ahead pages.
  514.  * We hope that ll_rw_blk() plug/unplug, coalescence, requests sort and the
  515.  * scheduler, will work enough for us to avoid too bad actuals IO requests.
  516.  */
  517.     ahead = 0;
  518.     while (ahead < max_ahead) {
  519.         ahead += PAGE_SIZE;
  520.         page_cache = try_to_read_ahead(filp, raend + ahead,
  521.                         page_cache);
  522.     }
  523. /*
  524.  * If we tried to read ahead some pages,
  525.  * If we tried to read ahead asynchronously,
  526.  *   Try to force unplug of the device in order to start an asynchronous
  527.  *   read IO request.
  528.  * Update the read-ahead context.
  529.  * Store the length of the current read-ahead window.
  530.  * Double the current max read ahead size.
  531.  *   That heuristic avoid to do some large IO for files that are not really
  532.  *   accessed sequentially.
  533.  */
  534.     if (ahead) {
  535.         if (reada_ok == 2) {
  536.             run_task_queue(&tq_disk);
  537.         }
  538.  
  539.         filp->f_ralen += ahead;
  540.         filp->f_rawin += filp->f_ralen;
  541.         filp->f_raend = raend + ahead + PAGE_SIZE;
  542.  
  543.         filp->f_ramax += filp->f_ramax;
  544.  
  545.         if (filp->f_ramax > max_readahead)
  546.             filp->f_ramax = max_readahead;
  547.  
  548. #ifdef PROFILE_READAHEAD
  549.         profile_readahead((reada_ok == 2), filp);
  550. #endif
  551.     }
  552.  
  553.     return page_cache;
  554. }
  555.  
  556. /*
  557.  * "descriptor" for what we're up to with a read.
  558.  * This allows us to use the same read code yet
  559.  * have multiple different users of the data that
  560.  * we read from a file.
  561.  *
  562.  * The simplest case just copies the data to user
  563.  * mode.
  564.  */
  565. typedef struct {
  566.     size_t written;
  567.     size_t count;
  568.     char * buf;
  569.     int error;
  570. } read_descriptor_t;
  571.  
  572. typedef int (*read_actor_t)(read_descriptor_t *, const char *, unsigned long);
  573.  
  574. /*
  575.  * This is a generic file read routine, and uses the
  576.  * inode->i_op->readpage() function for the actual low-level
  577.  * stuff.
  578.  *
  579.  * This is really ugly. But the goto's actually try to clarify some
  580.  * of the logic when it comes to error handling etc.
  581.  */
  582. static void do_generic_file_read(struct file * filp, loff_t *ppos, read_descriptor_t * desc, read_actor_t actor)
  583. {
  584.     struct dentry *dentry = filp->f_dentry;
  585.     struct inode *inode = dentry->d_inode;
  586.     size_t pos, pgpos, page_cache;
  587.     int reada_ok;
  588.     int max_readahead = get_max_readahead(inode);
  589.  
  590.     page_cache = 0;
  591.  
  592.     pos = *ppos;
  593.     pgpos = pos & PAGE_MASK;
  594. /*
  595.  * If the current position is outside the previous read-ahead window, 
  596.  * we reset the current read-ahead context and set read ahead max to zero
  597.  * (will be set to just needed value later),
  598.  * otherwise, we assume that the file accesses are sequential enough to
  599.  * continue read-ahead.
  600.  */
  601.     if (pgpos > filp->f_raend || pgpos + filp->f_rawin < filp->f_raend) {
  602.         reada_ok = 0;
  603.         filp->f_raend = 0;
  604.         filp->f_ralen = 0;
  605.         filp->f_ramax = 0;
  606.         filp->f_rawin = 0;
  607.     } else {
  608.         reada_ok = 1;
  609.     }
  610. /*
  611.  * Adjust the current value of read-ahead max.
  612.  * If the read operation stay in the first half page, force no readahead.
  613.  * Otherwise try to increase read ahead max just enough to do the read request.
  614.  * Then, at least MIN_READAHEAD if read ahead is ok,
  615.  * and at most MAX_READAHEAD in all cases.
  616.  */
  617.     if (pos + desc->count <= (PAGE_SIZE >> 1)) {
  618.         filp->f_ramax = 0;
  619.     } else {
  620.         unsigned long needed;
  621.  
  622.         needed = ((pos + desc->count) & PAGE_MASK) - pgpos;
  623.  
  624.         if (filp->f_ramax < needed)
  625.             filp->f_ramax = needed;
  626.  
  627.         if (reada_ok && filp->f_ramax < MIN_READAHEAD)
  628.                 filp->f_ramax = MIN_READAHEAD;
  629.         if (filp->f_ramax > max_readahead)
  630.             filp->f_ramax = max_readahead;
  631.     }
  632.  
  633.     for (;;) {
  634.         struct page *page, **hash;
  635.  
  636.         if (pos >= inode->i_size)
  637.             break;
  638.  
  639.         /*
  640.          * Try to find the data in the page cache..
  641.          */
  642.         hash = page_hash(inode, pos & PAGE_MASK);
  643.         page = __find_page(inode, pos & PAGE_MASK, *hash);
  644.         if (!page)
  645.             goto no_cached_page;
  646.  
  647. found_page:
  648. /*
  649.  * Try to read ahead only if the current page is filled or being filled.
  650.  * Otherwise, if we were reading ahead, decrease max read ahead size to
  651.  * the minimum value.
  652.  * In this context, that seems to may happen only on some read error or if 
  653.  * the page has been rewritten.
  654.  */
  655.         if (PageUptodate(page) || PageLocked(page))
  656.             page_cache = generic_file_readahead(reada_ok, filp, inode, pos & PAGE_MASK, page, page_cache);
  657.         else if (reada_ok && filp->f_ramax > MIN_READAHEAD)
  658.                 filp->f_ramax = MIN_READAHEAD;
  659.  
  660.         wait_on_page(page);
  661.  
  662.         if (!PageUptodate(page))
  663.             goto page_read_error;
  664.  
  665. success:
  666.         /*
  667.          * Ok, we have the page, it's up-to-date and ok,
  668.          * so now we can finally copy it to user space...
  669.          */
  670.     {
  671.         unsigned long offset, nr;
  672.  
  673.         offset = pos & ~PAGE_MASK;
  674.         nr = PAGE_SIZE - offset;
  675.         if (nr > inode->i_size - pos)
  676.             nr = inode->i_size - pos;
  677.  
  678.         /*
  679.          * The actor routine returns how many bytes were actually used..
  680.          * NOTE! This may not be the same as how much of a user buffer
  681.          * we filled up (we may be padding etc), so we can only update
  682.          * "pos" here (the actor routine has to update the user buffer
  683.          * pointers and the remaining count).
  684.          */
  685.         nr = actor(desc, (const char *) (page_address(page) + offset), nr);
  686.         pos += nr;
  687.         release_page(page);
  688.         if (nr && desc->count)
  689.             continue;
  690.         break;
  691.     }
  692.  
  693. no_cached_page:
  694.         /*
  695.          * Ok, it wasn't cached, so we need to create a new
  696.          * page..
  697.          */
  698.         if (!page_cache) {
  699.             page_cache = __get_free_page(GFP_USER);
  700.             /*
  701.              * That could have slept, so go around to the
  702.              * very beginning..
  703.              */
  704.             if (page_cache)
  705.                 continue;
  706.             desc->error = -ENOMEM;
  707.             break;
  708.         }
  709.  
  710.         /*
  711.          * Ok, add the new page to the hash-queues...
  712.          */
  713.         page = mem_map + MAP_NR(page_cache);
  714.         page_cache = 0;
  715.         add_to_page_cache(page, inode, pos & PAGE_MASK, hash);
  716.  
  717.         /*
  718.          * Error handling is tricky. If we get a read error,
  719.          * the cached page stays in the cache (but uptodate=0),
  720.          * and the next process that accesses it will try to
  721.          * re-read it. This is needed for NFS etc, where the
  722.          * identity of the reader can decide if we can read the
  723.          * page or not..
  724.          */
  725. /*
  726.  * We have to read the page.
  727.  * If we were reading ahead, we had previously tried to read this page,
  728.  * That means that the page has probably been removed from the cache before 
  729.  * the application process needs it, or has been rewritten.
  730.  * Decrease max readahead size to the minimum value in that situation.
  731.  */
  732.         if (reada_ok && filp->f_ramax > MIN_READAHEAD)
  733.             filp->f_ramax = MIN_READAHEAD;
  734.  
  735.         {
  736.             int error = inode->i_op->readpage(filp, page);
  737.             if (!error)
  738.                 goto found_page;
  739.             desc->error = error;
  740.             release_page(page);
  741.             break;
  742.         }
  743.  
  744. page_read_error:
  745.         /*
  746.          * We found the page, but it wasn't up-to-date.
  747.          * Try to re-read it _once_. We do this synchronously,
  748.          * because this happens only if there were errors.
  749.          */
  750.         {
  751.             int error = inode->i_op->readpage(filp, page);
  752.             if (!error) {
  753.                 wait_on_page(page);
  754.                 if (PageUptodate(page) && !PageError(page))
  755.                     goto success;
  756.                 error = -EIO; /* Some unspecified error occurred.. */
  757.             }
  758.             desc->error = error;
  759.             release_page(page);
  760.             break;
  761.         }
  762.     }
  763.  
  764.     *ppos = pos;
  765.     filp->f_reada = 1;
  766.     if (page_cache)
  767.         free_page(page_cache);
  768.     UPDATE_ATIME(inode);
  769. }
  770.  
  771. static int file_read_actor(read_descriptor_t * desc, const char *area, unsigned long size)
  772. {
  773.     unsigned long left;
  774.     unsigned long count = desc->count;
  775.  
  776.     if (size > count)
  777.         size = count;
  778.     left = __copy_to_user(desc->buf, area, size);
  779.     if (left) {
  780.         size -= left;
  781.         desc->error = -EFAULT;
  782.     }
  783.     desc->count = count - size;
  784.     desc->written += size;
  785.     desc->buf += size;
  786.     return size;
  787. }
  788.  
  789. /*
  790.  * This is the "read()" routine for all filesystems
  791.  * that can use the page cache directly.
  792.  */
  793. ssize_t generic_file_read(struct file * filp, char * buf, size_t count, loff_t *ppos)
  794. {
  795.     ssize_t retval;
  796.  
  797.     retval = -EFAULT;
  798.     if (access_ok(VERIFY_WRITE, buf, count)) {
  799.         retval = 0;
  800.         if (count) {
  801.             read_descriptor_t desc;
  802.  
  803.             desc.written = 0;
  804.             desc.count = count;
  805.             desc.buf = buf;
  806.             desc.error = 0;
  807.             do_generic_file_read(filp, ppos, &desc, file_read_actor);
  808.  
  809.             retval = desc.written;
  810.             if (!retval)
  811.                 retval = desc.error;
  812.         }
  813.     }
  814.     return retval;
  815. }
  816.  
  817. static int file_send_actor(read_descriptor_t * desc, const char *area, unsigned long size)
  818. {
  819.     ssize_t written;
  820.     unsigned long count = desc->count;
  821.     struct file *file = (struct file *) desc->buf;
  822.     struct inode *inode = file->f_dentry->d_inode;
  823.     mm_segment_t old_fs;
  824.  
  825.     if (size > count)
  826.         size = count;
  827.     down(&inode->i_sem);
  828.     old_fs = get_fs();
  829.     set_fs(KERNEL_DS);
  830.     written = file->f_op->write(file, area, size, &file->f_pos);
  831.     set_fs(old_fs);
  832.     up(&inode->i_sem);
  833.     if (written < 0) {
  834.         desc->error = written;
  835.         written = 0;
  836.     }
  837.     desc->count = count - written;
  838.     desc->written += written;
  839.     return written;
  840. }
  841.  
  842. asmlinkage ssize_t sys_sendfile(int out_fd, int in_fd, off_t *offset, size_t count)
  843. {
  844.     ssize_t retval;
  845.     struct file * in_file, * out_file;
  846.     struct inode * in_inode, * out_inode;
  847.  
  848.     lock_kernel();
  849.  
  850.     /*
  851.      * Get input file, and verify that it is ok..
  852.      */
  853.     retval = -EBADF;
  854.     in_file = fget(in_fd);
  855.     if (!in_file)
  856.         goto out;
  857.     if (!(in_file->f_mode & FMODE_READ))
  858.         goto fput_in;
  859.     retval = -EINVAL;
  860.     in_inode = in_file->f_dentry->d_inode;
  861.     if (!in_inode)
  862.         goto fput_in;
  863.     if (!in_inode->i_op || !in_inode->i_op->readpage)
  864.         goto fput_in;
  865.     retval = locks_verify_area(FLOCK_VERIFY_READ, in_inode, in_file, in_file->f_pos, count);
  866.     if (retval)
  867.         goto fput_in;
  868.  
  869.     /*
  870.      * Get output file, and verify that it is ok..
  871.      */
  872.     retval = -EBADF;
  873.     out_file = fget(out_fd);
  874.     if (!out_file)
  875.         goto fput_in;
  876.     if (!(out_file->f_mode & FMODE_WRITE))
  877.         goto fput_out;
  878.     retval = -EINVAL;
  879.     if (!out_file->f_op || !out_file->f_op->write)
  880.         goto fput_out;
  881.     out_inode = out_file->f_dentry->d_inode;
  882.     if (!out_inode)
  883.         goto fput_out;
  884.     retval = locks_verify_area(FLOCK_VERIFY_WRITE, out_inode, out_file, out_file->f_pos, count);
  885.     if (retval)
  886.         goto fput_out;
  887.  
  888.     retval = 0;
  889.     if (count) {
  890.         read_descriptor_t desc;
  891.         loff_t pos = 0, *ppos;
  892.  
  893.         retval = -EFAULT;
  894.         ppos = &in_file->f_pos;
  895.         if (offset) {
  896.             if (get_user(pos, offset))
  897.                 goto fput_out;
  898.             ppos = &pos;
  899.         }
  900.  
  901.         desc.written = 0;
  902.         desc.count = count;
  903.         desc.buf = (char *) out_file;
  904.         desc.error = 0;
  905.         do_generic_file_read(in_file, ppos, &desc, file_send_actor);
  906.  
  907.         retval = desc.written;
  908.         if (!retval)
  909.             retval = desc.error;
  910.         if (offset)
  911.             put_user(pos, offset);
  912.     }
  913.  
  914.  
  915. fput_out:
  916.     fput(out_file);
  917. fput_in:
  918.     fput(in_file);
  919. out:
  920.     unlock_kernel();
  921.     return retval;
  922. }
  923.  
  924. /*
  925.  * Semantics for shared and private memory areas are different past the end
  926.  * of the file. A shared mapping past the last page of the file is an error
  927.  * and results in a SIGBUS, while a private mapping just maps in a zero page.
  928.  *
  929.  * The goto's are kind of ugly, but this streamlines the normal case of having
  930.  * it in the page cache, and handles the special cases reasonably without
  931.  * having a lot of duplicated code.
  932.  *
  933.  * WSH 06/04/97: fixed a memory leak and moved the allocation of new_page
  934.  * ahead of the wait if we're sure to need it.
  935.  */
  936. static unsigned long filemap_nopage(struct vm_area_struct * area, unsigned long address, int no_share)
  937. {
  938.     struct file * file = area->vm_file;
  939.     struct dentry * dentry = file->f_dentry;
  940.     struct inode * inode = dentry->d_inode;
  941.     unsigned long offset, reada, i;
  942.     struct page * page, **hash;
  943.     unsigned long old_page, new_page;
  944.  
  945.     new_page = 0;
  946.     offset = (address & PAGE_MASK) - area->vm_start + area->vm_offset;
  947.     if (offset >= inode->i_size && (area->vm_flags & VM_SHARED) && area->vm_mm == current->mm)
  948.         goto no_page;
  949.  
  950.     /*
  951.      * Do we have something in the page cache already?
  952.      */
  953.     hash = page_hash(inode, offset);
  954.     page = __find_page(inode, offset, *hash);
  955.     if (!page)
  956.         goto no_cached_page;
  957.  
  958. found_page:
  959.     /*
  960.      * Ok, found a page in the page cache, now we need to check
  961.      * that it's up-to-date.  First check whether we'll need an
  962.      * extra page -- better to overlap the allocation with the I/O.
  963.      */
  964.     if (no_share && !new_page) {
  965.         new_page = __get_free_page(GFP_USER);
  966.         if (!new_page)
  967.             goto failure;
  968.     }
  969.  
  970.     if (PageLocked(page))
  971.         goto page_locked_wait;
  972.     if (!PageUptodate(page))
  973.         goto page_read_error;
  974.  
  975. success:
  976.     /*
  977.      * Found the page, need to check sharing and possibly
  978.      * copy it over to another page..
  979.      */
  980.     old_page = page_address(page);
  981.     if (!no_share) {
  982.         /*
  983.          * Ok, we can share the cached page directly.. Get rid
  984.          * of any potential extra pages.
  985.          */
  986.         if (new_page)
  987.             free_page(new_page);
  988.  
  989.         flush_page_to_ram(old_page);
  990.         return old_page;
  991.     }
  992.  
  993.     /*
  994.      * No sharing ... copy to the new page.
  995.      */
  996.     copy_page(new_page, old_page);
  997.     flush_page_to_ram(new_page);
  998.     release_page(page);
  999.     return new_page;
  1000.  
  1001. no_cached_page:
  1002.     /*
  1003.      * Try to read in an entire cluster at once.
  1004.      */
  1005.     reada   = offset;
  1006.     reada >>= PAGE_SHIFT + page_cluster;
  1007.     reada <<= PAGE_SHIFT + page_cluster;
  1008.  
  1009.     for (i = 1 << page_cluster; i > 0; --i, reada += PAGE_SIZE)
  1010.         new_page = try_to_read_ahead(file, reada, new_page);
  1011.  
  1012.     if (!new_page)
  1013.         new_page = __get_free_page(GFP_USER);
  1014.     if (!new_page)
  1015.         goto no_page;
  1016.  
  1017.     /*
  1018.      * During getting the above page we might have slept,
  1019.      * so we need to re-check the situation with the page
  1020.      * cache.. The page we just got may be useful if we
  1021.      * can't share, so don't get rid of it here.
  1022.      */
  1023.     page = find_page(inode, offset);
  1024.     if (page)
  1025.         goto found_page;
  1026.  
  1027.     /*
  1028.      * Now, create a new page-cache page from the page we got
  1029.      */
  1030.     page = mem_map + MAP_NR(new_page);
  1031.     new_page = 0;
  1032.     add_to_page_cache(page, inode, offset, hash);
  1033.  
  1034.     if (inode->i_op->readpage(file, page) != 0)
  1035.         goto failure;
  1036.  
  1037.     goto found_page;
  1038.  
  1039. page_locked_wait:
  1040.     __wait_on_page(page);
  1041.     if (PageUptodate(page))
  1042.         goto success;
  1043.     
  1044. page_read_error:
  1045.     /*
  1046.      * Umm, take care of errors if the page isn't up-to-date.
  1047.      * Try to re-read it _once_. We do this synchronously,
  1048.      * because there really aren't any performance issues here
  1049.      * and we need to check for errors.
  1050.      */
  1051.     if (inode->i_op->readpage(file, page) != 0)
  1052.         goto failure;
  1053.     wait_on_page(page);
  1054.     if (PageError(page))
  1055.         goto failure;
  1056.     if (PageUptodate(page))
  1057.         goto success;
  1058.  
  1059.     /*
  1060.      * Things didn't work out. Return zero to tell the
  1061.      * mm layer so, possibly freeing the page cache page first.
  1062.      */
  1063. failure:
  1064.     release_page(page);
  1065.     if (new_page)
  1066.         free_page(new_page);
  1067. no_page:
  1068.     return 0;
  1069. }
  1070.  
  1071. /*
  1072.  * Tries to write a shared mapped page to its backing store. May return -EIO
  1073.  * if the disk is full.
  1074.  */
  1075. static inline int do_write_page(struct inode * inode, struct file * file,
  1076.     const char * page, unsigned long offset)
  1077. {
  1078.     int retval;
  1079.     unsigned long size;
  1080.     loff_t loff = offset;
  1081.     mm_segment_t old_fs;
  1082.  
  1083.     size = offset + PAGE_SIZE;
  1084.     /* refuse to extend file size.. */
  1085.     if (S_ISREG(inode->i_mode)) {
  1086.         if (size > inode->i_size)
  1087.             size = inode->i_size;
  1088.         /* Ho humm.. We should have tested for this earlier */
  1089.         if (size < offset)
  1090.             return -EIO;
  1091.     }
  1092.     size -= offset;
  1093.     old_fs = get_fs();
  1094.     set_fs(KERNEL_DS);
  1095.     retval = -EIO;
  1096.     if (size == file->f_op->write(file, (const char *) page, size, &loff))
  1097.         retval = 0;
  1098.     set_fs(old_fs);
  1099.     return retval;
  1100. }
  1101.  
  1102. static int filemap_write_page(struct vm_area_struct * vma,
  1103.                   unsigned long offset,
  1104.                   unsigned long page,
  1105.                   int wait)
  1106. {
  1107.     int result;
  1108.     struct file * file;
  1109.     struct dentry * dentry;
  1110.     struct inode * inode;
  1111.  
  1112.     file = vma->vm_file;
  1113.     dentry = file->f_dentry;
  1114.     inode = dentry->d_inode;
  1115.     if (!file->f_op->write)
  1116.         return -EIO;
  1117.  
  1118.     /*
  1119.      * If a task terminates while we're swapping the page, the vma and
  1120.      * and file could be released ... increment the count to be safe.
  1121.      */
  1122.     file->f_count++;
  1123.  
  1124.     /* 
  1125.      * If this is a swapping operation rather than msync(), then
  1126.      * leave the actual IO, and the restoration of the file count,
  1127.      * to the kpiod thread.  Just queue the request for now.
  1128.      */
  1129.     if (!wait) {
  1130.         make_pio_request(file, offset, page);
  1131.         return 0;
  1132.     }
  1133.     
  1134.     down(&inode->i_sem);
  1135.     result = do_write_page(inode, file, (const char *) page, offset);
  1136.     up(&inode->i_sem);
  1137.     fput(file);
  1138.     return result;
  1139. }
  1140.  
  1141.  
  1142. /*
  1143.  * The page cache takes care of races between somebody
  1144.  * trying to swap something out and swap something in
  1145.  * at the same time..
  1146.  */
  1147. int filemap_swapout(struct vm_area_struct * vma, struct page * page)
  1148. {
  1149.     return filemap_write_page(vma, page->offset, page_address(page), 0);
  1150. }
  1151.  
  1152. static inline int filemap_sync_pte(pte_t * ptep, struct vm_area_struct *vma,
  1153.     unsigned long address, unsigned int flags)
  1154. {
  1155.     pte_t pte = *ptep;
  1156.     unsigned long page;
  1157.     int error;
  1158.  
  1159.     if (!(flags & MS_INVALIDATE)) {
  1160.         if (!pte_present(pte))
  1161.             return 0;
  1162.         if (!pte_dirty(pte))
  1163.             return 0;
  1164.         flush_page_to_ram(pte_page(pte));
  1165.         flush_cache_page(vma, address);
  1166.         set_pte(ptep, pte_mkclean(pte));
  1167.         flush_tlb_page(vma, address);
  1168.         page = pte_page(pte);
  1169.         atomic_inc(&mem_map[MAP_NR(page)].count);
  1170.     } else {
  1171.         if (pte_none(pte))
  1172.             return 0;
  1173.         flush_cache_page(vma, address);
  1174.         pte_clear(ptep);
  1175.         flush_tlb_page(vma, address);
  1176.         if (!pte_present(pte)) {
  1177.             swap_free(pte_val(pte));
  1178.             return 0;
  1179.         }
  1180.         page = pte_page(pte);
  1181.         if (!pte_dirty(pte) || flags == MS_INVALIDATE) {
  1182.             free_page(page);
  1183.             return 0;
  1184.         }
  1185.     }
  1186.     error = filemap_write_page(vma, address - vma->vm_start + vma->vm_offset, page, 1);
  1187.     free_page(page);
  1188.     return error;
  1189. }
  1190.  
  1191. static inline int filemap_sync_pte_range(pmd_t * pmd,
  1192.     unsigned long address, unsigned long size, 
  1193.     struct vm_area_struct *vma, unsigned long offset, unsigned int flags)
  1194. {
  1195.     pte_t * pte;
  1196.     unsigned long end;
  1197.     int error;
  1198.  
  1199.     if (pmd_none(*pmd))
  1200.         return 0;
  1201.     if (pmd_bad(*pmd)) {
  1202.         printk("filemap_sync_pte_range: bad pmd (%08lx)\n", pmd_val(*pmd));
  1203.         pmd_clear(pmd);
  1204.         return 0;
  1205.     }
  1206.     pte = pte_offset(pmd, address);
  1207.     offset += address & PMD_MASK;
  1208.     address &= ~PMD_MASK;
  1209.     end = address + size;
  1210.     if (end > PMD_SIZE)
  1211.         end = PMD_SIZE;
  1212.     error = 0;
  1213.     do {
  1214.         error |= filemap_sync_pte(pte, vma, address + offset, flags);
  1215.         address += PAGE_SIZE;
  1216.         pte++;
  1217.     } while (address < end);
  1218.     return error;
  1219. }
  1220.  
  1221. static inline int filemap_sync_pmd_range(pgd_t * pgd,
  1222.     unsigned long address, unsigned long size, 
  1223.     struct vm_area_struct *vma, unsigned int flags)
  1224. {
  1225.     pmd_t * pmd;
  1226.     unsigned long offset, end;
  1227.     int error;
  1228.  
  1229.     if (pgd_none(*pgd))
  1230.         return 0;
  1231.     if (pgd_bad(*pgd)) {
  1232.         printk("filemap_sync_pmd_range: bad pgd (%08lx)\n", pgd_val(*pgd));
  1233.         pgd_clear(pgd);
  1234.         return 0;
  1235.     }
  1236.     pmd = pmd_offset(pgd, address);
  1237.     offset = address & PGDIR_MASK;
  1238.     address &= ~PGDIR_MASK;
  1239.     end = address + size;
  1240.     if (end > PGDIR_SIZE)
  1241.         end = PGDIR_SIZE;
  1242.     error = 0;
  1243.     do {
  1244.         error |= filemap_sync_pte_range(pmd, address, end - address, vma, offset, flags);
  1245.         address = (address + PMD_SIZE) & PMD_MASK;
  1246.         pmd++;
  1247.     } while (address < end);
  1248.     return error;
  1249. }
  1250.  
  1251. static int filemap_sync(struct vm_area_struct * vma, unsigned long address,
  1252.     size_t size, unsigned int flags)
  1253. {
  1254.     pgd_t * dir;
  1255.     unsigned long end = address + size;
  1256.     int error = 0;
  1257.  
  1258.     dir = pgd_offset(vma->vm_mm, address);
  1259.     flush_cache_range(vma->vm_mm, end - size, end);
  1260.     while (address < end) {
  1261.         error |= filemap_sync_pmd_range(dir, address, end - address, vma, flags);
  1262.         address = (address + PGDIR_SIZE) & PGDIR_MASK;
  1263.         dir++;
  1264.     }
  1265.     flush_tlb_range(vma->vm_mm, end - size, end);
  1266.     return error;
  1267. }
  1268.  
  1269. /*
  1270.  * This handles (potentially partial) area unmaps..
  1271.  */
  1272. static void filemap_unmap(struct vm_area_struct *vma, unsigned long start, size_t len)
  1273. {
  1274.     filemap_sync(vma, start, len, MS_ASYNC);
  1275. }
  1276.  
  1277. /*
  1278.  * Shared mappings need to be able to do the right thing at
  1279.  * close/unmap/sync. They will also use the private file as
  1280.  * backing-store for swapping..
  1281.  */
  1282. static struct vm_operations_struct file_shared_mmap = {
  1283.     NULL,            /* no special open */
  1284.     NULL,            /* no special close */
  1285.     filemap_unmap,        /* unmap - we need to sync the pages */
  1286.     NULL,            /* no special protect */
  1287.     filemap_sync,        /* sync */
  1288.     NULL,            /* advise */
  1289.     filemap_nopage,        /* nopage */
  1290.     NULL,            /* wppage */
  1291.     filemap_swapout,    /* swapout */
  1292.     NULL,            /* swapin */
  1293. };
  1294.  
  1295. /*
  1296.  * Private mappings just need to be able to load in the map.
  1297.  *
  1298.  * (This is actually used for shared mappings as well, if we
  1299.  * know they can't ever get write permissions..)
  1300.  */
  1301. static struct vm_operations_struct file_private_mmap = {
  1302.     NULL,            /* open */
  1303.     NULL,            /* close */
  1304.     NULL,            /* unmap */
  1305.     NULL,            /* protect */
  1306.     NULL,            /* sync */
  1307.     NULL,            /* advise */
  1308.     filemap_nopage,        /* nopage */
  1309.     NULL,            /* wppage */
  1310.     NULL,            /* swapout */
  1311.     NULL,            /* swapin */
  1312. };
  1313.  
  1314. /* This is used for a general mmap of a disk file */
  1315.  
  1316. int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
  1317. {
  1318.     struct vm_operations_struct * ops;
  1319.     struct inode *inode = file->f_dentry->d_inode;
  1320.  
  1321.     if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE)) {
  1322.         ops = &file_shared_mmap;
  1323.         /* share_page() can only guarantee proper page sharing if
  1324.          * the offsets are all page aligned. */
  1325.         if (vma->vm_offset & (PAGE_SIZE - 1))
  1326.             return -EINVAL;
  1327.     } else {
  1328.         ops = &file_private_mmap;
  1329.         if (inode->i_op && inode->i_op->bmap &&
  1330.             (vma->vm_offset & (inode->i_sb->s_blocksize - 1)))
  1331.             return -EINVAL;
  1332.     }
  1333.     if (!inode->i_sb || !S_ISREG(inode->i_mode))
  1334.         return -EACCES;
  1335.     if (!inode->i_op || !inode->i_op->readpage)
  1336.         return -ENOEXEC;
  1337.     UPDATE_ATIME(inode);
  1338.     vma->vm_ops = ops;
  1339.     return 0;
  1340. }
  1341.  
  1342.  
  1343. /*
  1344.  * The msync() system call.
  1345.  */
  1346.  
  1347. static int msync_interval(struct vm_area_struct * vma,
  1348.     unsigned long start, unsigned long end, int flags)
  1349. {
  1350.     if (vma->vm_file && vma->vm_ops && vma->vm_ops->sync) {
  1351.         int error;
  1352.         error = vma->vm_ops->sync(vma, start, end-start, flags);
  1353.         if (!error && (flags & MS_SYNC)) {
  1354.             struct file * file = vma->vm_file;
  1355.             if (file) {
  1356.                 struct dentry * dentry = file->f_dentry;
  1357.                 struct inode * inode = dentry->d_inode;
  1358.                 down(&inode->i_sem);
  1359.                 error = file_fsync(file, dentry);
  1360.                 up(&inode->i_sem);
  1361.             }
  1362.         }
  1363.         return error;
  1364.     }
  1365.     return 0;
  1366. }
  1367.  
  1368. asmlinkage int sys_msync(unsigned long start, size_t len, int flags)
  1369. {
  1370.     unsigned long end;
  1371.     struct vm_area_struct * vma;
  1372.     int unmapped_error, error = -EINVAL;
  1373.  
  1374.     down(¤t->mm->mmap_sem);
  1375.     lock_kernel();
  1376.     if (start & ~PAGE_MASK)
  1377.         goto out;
  1378.     len = (len + ~PAGE_MASK) & PAGE_MASK;
  1379.     end = start + len;
  1380.     if (end < start)
  1381.         goto out;
  1382.     if (flags & ~(MS_ASYNC | MS_INVALIDATE | MS_SYNC))
  1383.         goto out;
  1384.     error = 0;
  1385.     if (end == start)
  1386.         goto out;
  1387.     /*
  1388.      * If the interval [start,end) covers some unmapped address ranges,
  1389.      * just ignore them, but return -EFAULT at the end.
  1390.      */
  1391.     vma = find_vma(current->mm, start);
  1392.     unmapped_error = 0;
  1393.     for (;;) {
  1394.         /* Still start < end. */
  1395.         error = -EFAULT;
  1396.         if (!vma)
  1397.             goto out;
  1398.         /* Here start < vma->vm_end. */
  1399.         if (start < vma->vm_start) {
  1400.             unmapped_error = -EFAULT;
  1401.             start = vma->vm_start;
  1402.         }
  1403.         /* Here vma->vm_start <= start < vma->vm_end. */
  1404.         if (end <= vma->vm_end) {
  1405.             if (start < end) {
  1406.                 error = msync_interval(vma, start, end, flags);
  1407.                 if (error)
  1408.                     goto out;
  1409.             }
  1410.             error = unmapped_error;
  1411.             goto out;
  1412.         }
  1413.         /* Here vma->vm_start <= start < vma->vm_end < end. */
  1414.         error = msync_interval(vma, start, vma->vm_end, flags);
  1415.         if (error)
  1416.             goto out;
  1417.         start = vma->vm_end;
  1418.         vma = vma->vm_next;
  1419.     }
  1420. out:
  1421.     unlock_kernel();
  1422.     up(¤t->mm->mmap_sem);
  1423.     return error;
  1424. }
  1425.  
  1426. /*
  1427.  * Write to a file through the page cache. This is mainly for the
  1428.  * benefit of NFS and possibly other network-based file systems.
  1429.  *
  1430.  * We currently put everything into the page cache prior to writing it.
  1431.  * This is not a problem when writing full pages. With partial pages,
  1432.  * however, we first have to read the data into the cache, then
  1433.  * dirty the page, and finally schedule it for writing. Alternatively, we
  1434.  * could write-through just the portion of data that would go into that
  1435.  * page, but that would kill performance for applications that write data
  1436.  * line by line, and it's prone to race conditions.
  1437.  *
  1438.  * Note that this routine doesn't try to keep track of dirty pages. Each
  1439.  * file system has to do this all by itself, unfortunately.
  1440.  *                            okir@monad.swb.de
  1441.  */
  1442. ssize_t
  1443. generic_file_write(struct file *file, const char *buf,
  1444.            size_t count, loff_t *ppos)
  1445. {
  1446.     struct dentry    *dentry = file->f_dentry; 
  1447.     struct inode    *inode = dentry->d_inode; 
  1448.     unsigned long    pos = *ppos;
  1449.     unsigned long    limit = current->rlim[RLIMIT_FSIZE].rlim_cur;
  1450.     struct page    *page, **hash;
  1451.     unsigned long    page_cache = 0;
  1452.     unsigned long    written;
  1453.     long        status, sync;
  1454.  
  1455.     if (!inode->i_op || !inode->i_op->updatepage)
  1456.         return -EIO;
  1457.  
  1458.     if (file->f_error) {
  1459.         int error = file->f_error;
  1460.         file->f_error = 0;
  1461.         return error;
  1462.     }
  1463.  
  1464.     sync    = file->f_flags & O_SYNC;
  1465.     written = 0;
  1466.  
  1467.     if (file->f_flags & O_APPEND)
  1468.         pos = inode->i_size;
  1469.  
  1470.     /*
  1471.      * Check whether we've reached the file size limit.
  1472.      */
  1473.     status = -EFBIG;
  1474.     if (pos >= limit) {
  1475.         send_sig(SIGXFSZ, current, 0);
  1476.         goto out;
  1477.     }
  1478.  
  1479.     status  = 0;
  1480.     /*
  1481.      * Check whether to truncate the write,
  1482.      * and send the signal if we do.
  1483.      */
  1484.     if (count > limit - pos) {
  1485.         send_sig(SIGXFSZ, current, 0);
  1486.         count = limit - pos;
  1487.     }
  1488.  
  1489.     while (count) {
  1490.         unsigned long bytes, pgpos, offset;
  1491.         /*
  1492.          * Try to find the page in the cache. If it isn't there,
  1493.          * allocate a free page.
  1494.          */
  1495.         offset = (pos & ~PAGE_MASK);
  1496.         pgpos = pos & PAGE_MASK;
  1497.         bytes = PAGE_SIZE - offset;
  1498.         if (bytes > count)
  1499.             bytes = count;
  1500.  
  1501.         hash = page_hash(inode, pgpos);
  1502.         page = __find_page(inode, pgpos, *hash);
  1503.         if (!page) {
  1504.             if (!page_cache) {
  1505.                 page_cache = __get_free_page(GFP_USER);
  1506.                 if (page_cache)
  1507.                     continue;
  1508.                 status = -ENOMEM;
  1509.                 break;
  1510.             }
  1511.             page = mem_map + MAP_NR(page_cache);
  1512.             add_to_page_cache(page, inode, pgpos, hash);
  1513.             page_cache = 0;
  1514.         }
  1515.  
  1516.         /* Get exclusive IO access to the page.. */
  1517.         wait_on_page(page);
  1518.         set_bit(PG_locked, &page->flags);
  1519.  
  1520.         /*
  1521.          * Do the real work.. If the writer ends up delaying the write,
  1522.          * the writer needs to increment the page use counts until he
  1523.          * is done with the page.
  1524.          */
  1525.         bytes -= copy_from_user((u8*)page_address(page) + offset, buf, bytes);
  1526.         status = -EFAULT;
  1527.         if (bytes)
  1528.             status = inode->i_op->updatepage(file, page, offset, bytes, sync);
  1529.  
  1530.         /* Mark it unlocked again and drop the page.. */
  1531.         clear_bit(PG_locked, &page->flags);
  1532.         wake_up(&page->wait);
  1533.         __free_page(page);
  1534.  
  1535.         if (status < 0)
  1536.             break;
  1537.  
  1538.         written += status;
  1539.         count -= status;
  1540.         pos += status;
  1541.         buf += status;
  1542.     }
  1543.     *ppos = pos;
  1544.     if (pos > inode->i_size)
  1545.         inode->i_size = pos;
  1546.  
  1547.     if (page_cache)
  1548.         free_page(page_cache);
  1549. out:
  1550.     return written ? written : status;
  1551. }
  1552.  
  1553. /*
  1554.  * Support routines for directory cacheing using the page cache.
  1555.  */
  1556.  
  1557. /*
  1558.  * Finds the page at the specified offset, installing a new page
  1559.  * if requested.  The count is incremented and the page is locked.
  1560.  *
  1561.  * Note: we don't have to worry about races here, as the caller
  1562.  * is holding the inode semaphore.
  1563.  */
  1564. unsigned long get_cached_page(struct inode * inode, unsigned long offset,
  1565.                 int new)
  1566. {
  1567.     struct page * page;
  1568.     struct page ** hash;
  1569.     unsigned long page_cache = 0;
  1570.  
  1571.     hash = page_hash(inode, offset);
  1572.     page = __find_page(inode, offset, *hash);
  1573.     if (!page) {
  1574.         if (!new)
  1575.             goto out;
  1576.         page_cache = get_free_page(GFP_USER);
  1577.         if (!page_cache)
  1578.             goto out;
  1579.         page = mem_map + MAP_NR(page_cache);
  1580.         add_to_page_cache(page, inode, offset, hash);
  1581.     }
  1582.     if (atomic_read(&page->count) != 2)
  1583.         printk(KERN_ERR "get_cached_page: page count=%d\n",
  1584.             atomic_read(&page->count));
  1585.     if (test_bit(PG_locked, &page->flags))
  1586.         printk(KERN_ERR "get_cached_page: page already locked!\n");
  1587.     set_bit(PG_locked, &page->flags);
  1588.     page_cache = page_address(page);
  1589.  
  1590. out:
  1591.     return page_cache;
  1592. }
  1593.  
  1594. /*
  1595.  * Unlock and free a page.
  1596.  */
  1597. void put_cached_page(unsigned long addr)
  1598. {
  1599.     struct page * page = mem_map + MAP_NR(addr);
  1600.  
  1601.     if (!test_bit(PG_locked, &page->flags))
  1602.         printk("put_cached_page: page not locked!\n");
  1603.     if (atomic_read(&page->count) != 2)
  1604.         printk("put_cached_page: page count=%d\n", 
  1605.             atomic_read(&page->count));
  1606.     clear_bit(PG_locked, &page->flags);
  1607.     wake_up(&page->wait);
  1608.     __free_page(page);
  1609. }
  1610.  
  1611.  
  1612. /* Add request for page IO to the queue */
  1613.  
  1614. static inline void put_pio_request(struct pio_request *p)
  1615. {
  1616.     *pio_last = p;
  1617.     p->next = NULL;
  1618.     pio_last = &p->next;
  1619. }
  1620.  
  1621. /* Take the first page IO request off the queue */
  1622.  
  1623. static inline struct pio_request * get_pio_request(void)
  1624. {
  1625.     struct pio_request * p = pio_first;
  1626.     pio_first = p->next;
  1627.     if (!pio_first)
  1628.         pio_last = &pio_first;
  1629.     return p;
  1630. }
  1631.  
  1632. /* Make a new page IO request and queue it to the kpiod thread */
  1633.  
  1634. static inline void make_pio_request(struct file *file,
  1635.                     unsigned long offset,
  1636.                     unsigned long page)
  1637. {
  1638.     struct pio_request *p;
  1639.  
  1640.     atomic_inc(&mem_map[MAP_NR(page)].count);
  1641.  
  1642.     /* 
  1643.      * We need to allocate without causing any recursive IO in the
  1644.      * current thread's context.  We might currently be swapping out
  1645.      * as a result of an allocation made while holding a critical
  1646.      * filesystem lock.  To avoid deadlock, we *MUST* not reenter
  1647.      * the filesystem in this thread.
  1648.      *
  1649.      * We can wait for kswapd to free memory, or we can try to free
  1650.      * pages without actually performing further IO, without fear of
  1651.      * deadlock.  --sct
  1652.      */
  1653.  
  1654.     while ((p = kmem_cache_alloc(pio_request_cache, GFP_BUFFER)) == NULL) {
  1655.         if (try_to_free_pages(__GFP_WAIT))
  1656.             continue;
  1657.         current->state = TASK_INTERRUPTIBLE;
  1658.         schedule_timeout(HZ/10);
  1659.     }
  1660.     
  1661.     p->file   = file;
  1662.     p->offset = offset;
  1663.     p->page   = page;
  1664.  
  1665.     put_pio_request(p);
  1666.     wake_up(&pio_wait);
  1667. }
  1668.  
  1669.  
  1670. /*
  1671.  * This is the only thread which is allowed to write out filemap pages
  1672.  * while swapping.
  1673.  * 
  1674.  * To avoid deadlock, it is important that we never reenter this thread.
  1675.  * Although recursive memory allocations within this thread may result
  1676.  * in more page swapping, that swapping will always be done by queuing
  1677.  * another IO request to the same thread: we will never actually start
  1678.  * that IO request until we have finished with the current one, and so
  1679.  * we will not deadlock.  
  1680.  */
  1681.  
  1682. int kpiod(void * unused)
  1683. {
  1684.     struct task_struct *tsk = current;
  1685.     struct wait_queue wait = { tsk, };
  1686.     struct inode * inode;
  1687.     struct dentry * dentry;
  1688.     struct pio_request * p;
  1689.     
  1690.     tsk->session = 1;
  1691.     tsk->pgrp = 1;
  1692.     strcpy(tsk->comm, "kpiod");
  1693.     sigfillset(&tsk->blocked);
  1694.     init_waitqueue(&pio_wait);
  1695.     /*
  1696.      * Mark this task as a memory allocator - we don't want to get caught
  1697.      * up in the regular mm freeing frenzy if we have to allocate memory
  1698.      * in order to write stuff out.
  1699.      */
  1700.     tsk->flags |= PF_MEMALLOC;
  1701.  
  1702.     lock_kernel();
  1703.     
  1704.     pio_request_cache = kmem_cache_create("pio_request", 
  1705.                           sizeof(struct pio_request),
  1706.                           0, SLAB_HWCACHE_ALIGN, 
  1707.                           NULL, NULL);
  1708.     if (!pio_request_cache)
  1709.         panic ("Could not create pio_request slab cache");
  1710.  
  1711.     while (1) {
  1712.         tsk->state = TASK_INTERRUPTIBLE;
  1713.         add_wait_queue(&pio_wait, &wait);
  1714.         if (!pio_first)
  1715.             schedule();
  1716.         remove_wait_queue(&pio_wait, &wait);
  1717.         tsk->state = TASK_RUNNING;
  1718.  
  1719.         while (pio_first) {
  1720.             p = get_pio_request();
  1721.             dentry = p->file->f_dentry;
  1722.             inode = dentry->d_inode;
  1723.             
  1724.             down(&inode->i_sem);
  1725.             do_write_page(inode, p->file,
  1726.                       (const char *) p->page, p->offset);
  1727.             up(&inode->i_sem);
  1728.             fput(p->file);
  1729.             free_page(p->page);
  1730.             kmem_cache_free(pio_request_cache, p);
  1731.         }
  1732.     }
  1733. }
  1734.